// mmo_game_server/server_management/etcd_client.go
package server_management

import (
    "context"
    "log"
    "time"

    "go.etcd.io/etcd/clientv3"
)

var etcdClient *clientv3.Client

// InitEtcdClient 初始化etcd客户端
func InitEtcdClient(endpoints []string) error {
    var err error
    etcdClient, err = clientv3.New(clientv3.Config{
        Endpoints:   endpoints,
        DialTimeout: 5 * time.Second,
    })
    if err != nil {
        log.Fatalf("Failed to connect to etcd: %v", err)
        return err
    }
    return nil
}

// RegisterService 注册服务到etcd
func RegisterService(serviceName, serviceAddr string) error {
    ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
    _, err := etcdClient.Put(ctx, serviceName, serviceAddr)
    cancel()
    if err != nil {
        log.Printf("Failed to register service %s to etcd: %v", serviceName, err)
        return err
    }
    return nil
}

// DiscoverService 从etcd发现服务
func DiscoverService(serviceName string) (string, error) {
    ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
    resp, err := etcdClient.Get(ctx, serviceName)
    cancel()
    if err != nil {
        log.Printf("Failed to discover service %s from etcd: %v", serviceName, err)
        return "", err
    }
    if len(resp.Kvs) == 0 {
        return "", nil
    }
    return string(resp.Kvs[0].Value), nil
}